<?php
/**
 * Yupoo相册插件,支持在编辑页面进行照片上传 照片插入
 * 
 * @package Yupoo!
 * @author John.H
 * @version 1.0.0
 * @link http://typecho.org
 */

define('TYUPOO_PLUGIN_VERSION', '1.0.0');

class Tyupoo_Plugin implements Typecho_Plugin_Interface
{
	private static $pluginName 		= 'Tyupoo';
	
	private static $pluginVersion 	= '1.0.0'; 
	
    /**
     * 激活插件方法,如果激活失败,直接抛出异常
     * 
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function activate()
    {
        //添加访问入口
		Helper::addPanel(1, 'Tyupoo/auth.php', _t('Tyupoo授权'), _t('Tyupoo授权'), 'administrator', true);
		Helper::addPanel(1, 'Tyupoo/album.php', _t('Tyupoo相册'), _t('Tyupoo相册'), 'administrator', true);
		Helper::addPanel(1, 'Tyupoo/upload.php', _t('Tyupoo上传'), _t('Tyupoo上传'), 'administrator', true);
		
		Typecho_Plugin::factory('admin/write-post.php')->bottom = array('Tyupoo_Plugin', 'page');
		Typecho_Plugin::factory('admin/write-page.php')->bottom = array('Tyupoo_Plugin', 'page');
    }
    
    /**
     * 禁用插件方法,如果禁用失败,直接抛出异常
     * 
     * @static
     * @access public
     * @return void
     * @throws Typecho_Plugin_Exception
     */
    public static function deactivate()
    {
        Helper::removePanel(1, 'Tyupoo/auth.php');
		Helper::removePanel(1, 'Tyupoo/album.php');
		Helper::removePanel(1, 'Tyupoo/upload.php');
    }

	private static function update()
	{
		$pluginName = self::$pluginName;

		//插件升级
		$db = Typecho_Db::get();
		//禁用插件
		Tyupoo_Plugin::deactivate();
		Typecho_Plugin::deactivate($pluginName);
		$db->query( $db->update('table.options')
			->rows(array('value' => serialize(Typecho_Plugin::export())))
			->where('name = ?', 'plugins'));
		$db->query($db->delete('table.options')->where('name = ?', 'plugin:'.$pluginName));
		//重新激活
		Tyupoo_Plugin::activate();
		Typecho_Plugin::activate($pluginName);
		$db->query( $db->update('table.options')
			->rows(array('value' => serialize(Typecho_Plugin::export())))
			->where('name = ?', 'plugins'));
		$form = new Typecho_Widget_Helper_Form();
		call_user_func(array($pluginName.'_Plugin', 'config'), $form);
		$options = $form->getValues();
		if ( ! empty($options))
		{
			$db->query( $db->insert('table.options')
					   ->rows(array(
									'name'=>'plugin:' . $pluginName,
									'user'=>0,
									'value'=>serialize($options)
									)));			
		}

		return true;
	}
    
    /**
     * 获取插件配置面板
     * 
     * @access public
     * @param Typecho_Widget_Helper_Form $form 配置面板
     * @return void
     */
    public static function config(Typecho_Widget_Helper_Form $form)
    {
        echo '<div class="message success typecho-radius-topleft typecho-radius-topright typecho-radius-bottomleft typecho-radius-bottomright">
                <ul>
                    <li>插件安装说明:</li>
                    <li>1.请配置Yupoo API应用程序认证类型为 "桌面应用" ,否则插件无法正常使用</li>
                    <li>2.Yupoo API申请地址: <a href="http://www.yupoo.com/services/api/apply" target="_blank">申请API KEY</a> </li>
                </ul>
              </div>';

        /** API配置 */
        $apiKey      	= new Typecho_Widget_Helper_Form_Element_Text('apiKey', NULL, '', _t('Api Key:'));
        $sharedSecret 	= new Typecho_Widget_Helper_Form_Element_Text('sharedSecret', NULL, '', _t('Shared Secret:'));
        $authToken   	= new Typecho_Widget_Helper_Form_Element_Hidden('authToken', NULL, '');
        $userID      	= new Typecho_Widget_Helper_Form_Element_Hidden('userID', NULL, '');
		//插件版本,用于判断是否执行升级操作
		$pluginVersion  = new Typecho_Widget_Helper_Form_Element_Hidden('pluginVer', NULL, TYUPOO_PLUGIN_VERSION);
        //$albumId     	= new Typecho_Widget_Helper_Form_Element_Hidden('albumId', NULL, 'notInAlbum');
        
		$form->addInput($apiKey);
        $form->addInput($sharedSecret);
        $form->addInput($authToken);
        $form->addInput($userID);
		$form->addInput($pluginVersion);
        //$form->addInput($albumId);
    }
    
    /**
     * 个人用户的配置面板
     * 
     * @access public
     * @param Typecho_Widget_Helper_Form $form
     * @return void
     */
    public static function personalConfig(Typecho_Widget_Helper_Form $form){}
	
	/**
	 *在编辑页面上的交互
	 */
	public static function page($post)
	{		
		$widgetOptions 	= Helper::options();
		$options 		= $widgetOptions->plugin('Tyupoo'); 
		$adminUrl 		= $widgetOptions->adminUrl;
		$configUrl 		= "{$adminUrl}/option-plugin.php?config=Tyupoo";	
		$normalUrl 		= Helper::url('Tyupoo/album.php');
		$uploadUrl		= Helper::url('Tyupoo/upload.php');
		$preScript 		= <<<EOF
		var con = new Element('span',{
			styles : {
				'float' : 'right',
				'padding-right' : '5px'
			}
		});
		
		var cite = $('auto-save-message');
		con.inject(cite, 'before');
		
		function showTyupoo(){
			con.html('<a id="tyupoo" href="#">Yupoo</a><a id="tyupoo_up" href="#">!&nbsp;</a>');
			$('tyupoo').addEvent('click',function(){
				tyupoo.centerFrame.show('{$normalUrl}');
				return false;
			});
			$('tyupoo_up').addEvent('click',function(){
				tyupoo.centerFrame.show('{$uploadUrl}');
				return false;
			});
		}
EOF;
		/*if ( ! empty($options->pluginVer) && $options->pluginVer != self::$pluginVersion)
		{
			self::update();
			$html = "插件已经升级,请重新<a href=\"{$configUrl}\">配置</a>";
		}
		else*/if (empty($options->apiKey) || empty($options->sharedSecret))
		{
			//用户未完成必要设置项
			$html = "请先完成Tyupoo插件<a href=\"{$configUrl}\">配置</a>";
		}
		elseif (empty($options->authToken))
		{
			//用户未获取认证码
			include 'Tyupoo.php';
			$typ 			= new Tyupoo($options->apiKey, $options->sharedSecret, '');
			$frob			= $typ->getFrob();
			if ($frob === null)
			{
				$html = 'Yupoo接口连接超时';
			}
			elseif ($frob === '')
			{
				$html = "认证出错,请确认Typoo插件<a href=\"{$configUrl}\">配置</a>正确";
			}
			else
			{
				$authUrl 		= $typ->getAuthUrl($frob);
				$authTokenUrl 	= Helper::url('Tyupoo/auth.php') . "&frob={$frob}";
				$html 			= "点击此<a id=\"authLink\" href=\"{$authUrl}\" target=\"_blank\">链接</a>完成Yupoo认证";
				$script			= <<<EOF
				$('authLink').addEvent('click', function(){
					setTimeout(function(){
						Pmoo.Ajax.get('{$authTokenUrl}', function(r, req){
							tyupoo.besideTip.hide();
							var result = r.responseText.split('-', 2);
							var code   = parseInt(result[0]);
							var msg    = result[1];
							if (code != 1){
								con.html('认证失败:'+msg+',请刷新页面后重试');
							}
							else{
								showTyupoo();
							}
						});
					}, 1000);
					tyupoo.besideTip.showLoading(con, '正在获取验证');
					return true;
				});
EOF;
			}

		}
		else
		{
			//通过验证后默认展现相册页面
			$html   = 'Yupoo! is coming';
			$script = 'showTyupoo()';
		}
		$html = empty($html) ? '' : $html;
		$script = empty($script) ? '' : $script;
		$scriptFilePre = $widgetOptions->pluginUrl . '/Tyupoo/js';
		$styleFilePre  = $widgetOptions->pluginUrl . '/Tyupoo/css';
		
		echo <<<EOF
		<link rel="stylesheet" type="text/css" href="{$styleFilePre}/tyupoo.css" />
		<script type="text/javascript" src="{$scriptFilePre}/Pmoo/Pmoo.js"></script>
		<script type="text/javascript" src="{$scriptFilePre}/Pmoo/Pmoo.Ajax.js"></script>
		<script type="text/javascript" src="{$scriptFilePre}/Pmoo/Pmoo.Tip2.js"></script>
		<script type="text/javascript" src="{$scriptFilePre}/Pmoo/Pmoo.Mask.js"></script>
		<script type="text/javascript" src="{$scriptFilePre}/tyupoo.js"></script>
		<script type="text/javascript">
		Pmoo.Mask.ini_set('insertDom', true);
		(function(){
		
		{$preScript}
		
		con.html('{$html}');
		{$script}
		
		})();
		</script>
EOF;
		return false;
	}
    
}
